package viewer;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import model.Flights;
import model.Points;
import model.Routes;
import client.IOCLient;
import java.util.ArrayList;
import java.util.Comparator;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class MainWindow extends javax.swing.JFrame {

    public Points points = new Points();
    public Routes routes = new Routes();
    public Flights flights = new Flights();
    public Flights flightsSearch = new Flights();
    public Search sear = new Search();
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jList1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu5;
    private javax.swing.JMenu jMenu6;
    private javax.swing.JMenu jMenu7;
    private javax.swing.JMenu jMenu8;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    public javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration//GEN-END:variables
    /**
     * Вид открытия окна: 0 - добавление; 1 - поиск; 2 - редактирование
     */
    public static int openKind = 0;
    public static String nameId = "";

    /**
     * Creates new form Qas
     */
    public MainWindow() throws IOException {
        initComponents();
        this.setLocationRelativeTo(null);
        DefaultTableCellRenderer r = (DefaultTableCellRenderer) jTable1.getDefaultRenderer(String.class);
        r.setHorizontalAlignment(JLabel.CENTER);
        r.setVerticalAlignment(JLabel.TOP);
        jTable1.setAutoCreateColumnsFromModel(false);
        TableRowSorter<TableModel> sorter = new TableRowSorter(jTable1.getModel()) {

            @Override
            public Comparator<?> getComparator(int column) {
                // для нулевой строки
                if (column == 0) {
                    return new Comparator<String>() {

                        @Override
                        public int compare(String s1, String s2) {
                            return Integer.parseInt(s1) - Integer.parseInt(s2);
                        }
                    };
                }
                // для всех остальных
                return super.getComparator(column);
            }
        };
        jTable1.setRowSorter(sorter);
        this.jMenu1.setEnabled(false);
        this.jMenu2.setEnabled(false);
        this.jMenu3.setEnabled(false);
        this.jMenu5.setEnabled(false);
        this.jMenu6.setEnabled(false);
        this.jMenu7.setEnabled(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jButton1 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton3 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        jMenu5 = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();
        jMenu7 = new javax.swing.JMenu();
        jMenu6 = new javax.swing.JMenu();
        jMenu8 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Авиарейсы");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "№ рейса", "Аэробус", "Пункт вылета", "Пункт прибытия", "Время вылета", "Путевое время"
            }
        ));
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(30);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(100);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(100);
        jTable1.getColumnModel().getColumn(4).setResizable(false);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(55);
        jTable1.getColumnModel().getColumn(5).setResizable(false);
        jTable1.getColumnModel().getColumn(5).setPreferredWidth(60);

        jLabel1.setText("Допольнительная информация:");

        jTextPane1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextPane1KeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextPane1KeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(jTextPane1);

        jButton1.setText("Найти");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jScrollPane3.setViewportView(jList1);

        jButton3.setText("Очистить");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel2.setText("Представьтесь");

        jButton2.setText("OK");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jMenu1.setText("Добавить");
        jMenu1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu1MouseClicked(evt);
            }
        });
        jMenuBar1.add(jMenu1);

        jMenu2.setLabel("Удалить");
        jMenu2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu2MouseClicked(evt);
            }
        });
        jMenuBar1.add(jMenu2);

        jMenu5.setText("Изменить");
        jMenu5.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu5MouseClicked(evt);
            }
        });
        jMenuBar1.add(jMenu5);

        jMenu3.setText("Сохранить");
        jMenu3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu3MouseClicked(evt);
            }
        });
        jMenuBar1.add(jMenu3);

        jMenu7.setText("Загрузить");
        jMenu7.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu7MouseClicked(evt);
            }
        });
        jMenuBar1.add(jMenu7);

        jMenu6.setText("Поиск");
        jMenu6.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu6MouseClicked(evt);
            }
        });
        jMenuBar1.add(jMenu6);

        jMenu8.setText("Выход");
        jMenu8.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu8MouseClicked(evt);
            }
        });
        jMenuBar1.add(jMenu8);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 604, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 604, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE))
                        .addGap(133, 133, 133))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButton2)))
                        .addGap(0, 284, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3))
                .addGap(18, 18, 18)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Переход на форму добавления новой записи
     */
    private void jMenu1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu1MouseClicked
        jTextField1.setText("");
        this.flights = IOCLient.reload(nameId);
        InputWindow.fill(Convertor.ToArrayList(flights),this);
        try {
            MainWindow.openKind = 0;
            JFrame myWindow = new InputWindow(this);
            myWindow.setVisible(true);
            myWindow.setTitle("Добавление записи");
            myWindow.setLocationRelativeTo(null);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jMenu1MouseClicked

    /**
     * Переход на форму поиска
     */
    private void jMenu6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu6MouseClicked
        jTextField1.setText("");
        try {
            this.flights = IOCLient.reload(nameId);
            InputWindow.fill(Convertor.ToArrayList(flights),this);
            MainWindow.openKind = 1;
            JFrame myWindow = new InputWindow(this);
            myWindow.setSize(460, 400);
            myWindow.setVisible(true);
            myWindow.setTitle("Форма поиска");
            myWindow.setLocationRelativeTo(null);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jMenu6MouseClicked
    /**
     * Сохранение всей таблицы в файл
     */
    private void jMenu3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu3MouseClicked
        jTextField1.setText("");

        int response = JOptionPane.showOptionDialog(null,
                "Перезаписать данные?",
                "Overwrite", 1, JOptionPane.INFORMATION_MESSAGE, null, null, null);
        Boolean overwrite = false;
        if (response != 2) {
            if (response == 1) {
                overwrite = false;
            } else {
                overwrite = true;
            }
            this.flights = IOCLient.reload(nameId);
            InputWindow.fill(Convertor.ToArrayList(flights),this);
            IOCLient.saveDataToServer("flightsServ.xml", flights, overwrite, MainWindow.nameId);
            IOCLient.saveDataToServer("routesServ.xml", routes, overwrite, MainWindow.nameId);
            IOCLient.saveDataToServer("pointsServ.xml", points, overwrite, MainWindow.nameId);
        }
    }//GEN-LAST:event_jMenu3MouseClicked
    /**
     * Переход на форму редактирования текущей строки
     */
    private void jMenu5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu5MouseClicked
        if (jTable1.getSelectedRow() == -1) {
            jTextField1.setText("Выберите строку для работы");
        } else {
            jTextField1.setText("");
            flights = IOCLient.reload(nameId);
            DefaultTableModel mod = (DefaultTableModel) jTable1.getModel();
            Vector<String> v = (Vector<String>) mod.getDataVector().elementAt(jTable1.getSelectedRow());
            if (flights.checkFlightsNumber(Integer.parseInt(v.get(0)))) {
                int response = JOptionPane.showOptionDialog(null,
                        "Полета больше нет на сервере. Повторите попытку",
                        "Сожалеем...", -1, JOptionPane.INFORMATION_MESSAGE, null, null, null);
                flights = IOCLient.reload(nameId);
                InputWindow.fill(Convertor.ToArrayList(flights),this);
            } else {
                try {
                    MainWindow.openKind = 2;
                    JFrame myWindow = new InputWindow(this);
                    myWindow.setSize(460, 400);
                    myWindow.setVisible(true);
                    myWindow.setTitle("Форма редактирования");
                    myWindow.setLocationRelativeTo(null);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_jMenu5MouseClicked
    /**
     * Удаление текущей строки
     */
    private void jMenu2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu2MouseClicked
        if (jTable1.getSelectedRow() == -1) {
            jTextField1.setText("Выберите строку для работы");
        } else {
            jTextField1.setText("");
            DefaultTableModel mod = (DefaultTableModel) jTable1.getModel();
            try {
                flights = IOCLient.reload(nameId);
                Vector<String> v = (Vector<String>) mod.getDataVector().elementAt(jTable1.getSelectedRow());
                int flightNumber = Integer.parseInt(v.get(0));
                if (flights.checkFlightsNumber(flightNumber)) {
                    int response = JOptionPane.showOptionDialog(null,
                            "Полета больше нет на сервере. Повторите попытку",
                            "Сожалеем...", -1, JOptionPane.INFORMATION_MESSAGE, null, null, null);
                    flights = IOCLient.reload(nameId);
                    InputWindow.fill(Convertor.ToArrayList(flights),this);
                } else {
                    flights = IOCLient.delete(flightNumber, MainWindow.nameId);
                    InputWindow.fill(Convertor.ToArrayList(flights),this);
                }
            } catch (ArrayIndexOutOfBoundsException e) {
            }
        }
    }//GEN-LAST:event_jMenu2MouseClicked
    /**
     * Загрузка базы
     */
    private void jMenu7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu7MouseClicked
        jTextField1.setText("");
        flights = (Flights) IOCLient.loadDataFromServer("flightsServ.xml", Flights.class, MainWindow.nameId);
        routes = (Routes) IOCLient.loadDataFromServer("routesServ.xml", Routes.class, MainWindow.nameId);
        points = (Points) IOCLient.loadDataFromServer("pointsServ.xml", Points.class, MainWindow.nameId);
        InputWindow.fill(Convertor.ToArrayList(flights),this);
    }//GEN-LAST:event_jMenu7MouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        InputWindow.fill(Convertor.ToArrayList(sear.searchFirst(flights, jTextPane1.getText())),this);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTextPane1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextPane1KeyPressed
        if (evt.getKeyCode() == 10) {
            evt.consume();
        }
    }//GEN-LAST:event_jTextPane1KeyPressed

    /**
     * Обработка ввода запроса
     */
    private void jTextPane1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextPane1KeyReleased
        // TODO add your handling code here:
        if (jList1.getModel().getSize() > 0) {
            //Down
            if (evt.getKeyCode() == 40) {
                jList1.setSelectedIndex(jList1.getSelectedIndex() + 1);
                jTextPane1.setText(jList1.getSelectedValue().toString());
            }
            //Up
            if (evt.getKeyCode() == 38) {
                jList1.setSelectedIndex(jList1.getSelectedIndex() - 1);
                jTextPane1.setText(jList1.getSelectedValue().toString());
            }
        }
        String text = jTextPane1.getText();
        if ((evt.getKeyCode() != 40) && (evt.getKeyCode() != 38)) {
            if (evt.getKeyCode() == 10) {
                InputWindow.fill(Convertor.ToArrayList(sear.searchFirst(flights, jTextPane1.getText())),this);
            } else {
                DefaultListModel lm = new DefaultListModel();
                lm.clear();

                if (!text.isEmpty()) {
                    ArrayList<String> arr = sear.search(flights, text);
                    for (String x : arr) {
                        lm.addElement(x);
                    }
                } else {
                    lm.clear();
                }
                jList1.setModel(lm);
            }
        }
    }//GEN-LAST:event_jTextPane1KeyReleased
    /**
     * Очистка результатов поиска
     */
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        InputWindow.fill(Convertor.ToArrayList(flights),this);
}//GEN-LAST:event_jButton3ActionPerformed

    /**
     * Подпись клиента
     */
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        if (!jTextField2.getText().isEmpty()) {
            MainWindow.nameId = jTextField2.getText();
            this.jMenu1.setEnabled(true);
            this.jMenu2.setEnabled(true);
            this.jMenu3.setEnabled(true);
            this.jMenu5.setEnabled(true);
            this.jMenu6.setEnabled(true);
            this.jMenu7.setEnabled(true);
            jLabel2.setText("Здравствуйте, " + jTextField2.getText() + "!");
            jTextField2.setVisible(false);
            jButton2.setVisible(false);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * Выход
     */
    private void jMenu8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu8MouseClicked
        // TODO add your handling code here:
        int response = JOptionPane.showOptionDialog(null,
                "Покинуть программу?",
                "Выход", 0, JOptionPane.INFORMATION_MESSAGE, null, null, null);
        if (response == 0) {
            IOCLient.exit(nameId);
            // <editor-fold defaultstate="collapsed" desc="comment">
            System.exit(0);// </editor-fold>

        }
    }//GEN-LAST:event_jMenu8MouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new MainWindow().setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
}
